package com.whsxt.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;

/**
 * @Author: caoqingwen
 * @CreateTime: 2021-03-23 14:43
 * @Description:
 */
@EnableConfigurationProperties(value = WxProperties.class)
@Configuration
@Slf4j
public class WxAutoConfiguration {


    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private WxProperties wxProperties;

    @Autowired
    private StringRedisTemplate redisTemplate;


    private String wxAccessToken;


    /**
     * 这个注解的作用：spring实现了这个注解的规范
     * 所有bean对象创建完之后，项目启动完成之前执行
     * 限制：方法不能有返回值，也不能有参数
     */
    @PostConstruct
    public void initToken() {
        getAccessToken();
    }


    /**
     * 获取微信的accessToken
     */
    @Scheduled(initialDelay = 0, fixedRate = 7100 * 1000)
    public void getAccessToken() {
        String accessTokenUrl = wxProperties.getAccessTokenUrl();
        String realUrl = String.format(accessTokenUrl, wxProperties.getAppId(), wxProperties.getAppSecret());
        String jsonStr = restTemplate.getForObject(realUrl, String.class);
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        String accessToken = jsonObject.getString("access_token");
        if (!StringUtils.isEmpty(accessToken)) {
            //保存起来
            wxAccessToken = accessToken;
        } else {
            log.error("获取微信access_token失败");
        }
    }


    public String getWxAccessToken() {
        return wxAccessToken;
    }

    public void setWxAccessToken(String wxAccessToken) {
        this.wxAccessToken = wxAccessToken;
    }
}
